package LocalCRM::DBI::Invoice;

use base 'LocalCRM::DBI';
use Class::Date;

sub getById
{
    my $self = shift;

    if ( scalar(@_)==1 && (my $id = $_[0]) )
    {
	my $sth = $self->{_db}->prepare
	(
	    'SELECT *,`invoice`.`id` AS `id`'
	    .' FROM `invoice`'
		.' JOIN `contract` ON `contract`.`id`=`invoice`.`contract_id`'
		.' JOIN `customer` ON `customer`.`account_id`=`contract`.`account_id`'
		.' JOIN `executive` ON `executive`.`id`=`contract`.`executive_id`'
	    .' WHERE `invoice`.`id`=?'
	    .' LIMIT 1'
	);

	if ( $sth->execute($id) )
	{
	    my $row = $sth->fetchrow_hashref();

	    foreach my $key ( keys %{$row} )
	    {
		$row->{$key} =~ s/\\\"/\"/g;
	    }

	    $row->{date} = new Class::Date $row->{date};

	    return $row;
	}
    }
    elsif( scalar(@_)==2 )
    {
	return $self->SUPER::getById(@_);
    }
}

sub getItemsByInvoiceId
{
    my $self = shift;
    my @data;

    my $sth = $self->{_db}->prepare
    (
	'SELECT * FROM `invoice_items`'
	.' JOIN `service_name` ON `service_name`.`id`=`invoice_items`.`service_name_id`'
	.' WHERE `invoice_id`=?'
	.' ORDER BY `invoice_items`.`id` ASC'
    );

    if ( $sth->execute($_[0]) )
    {
	while ( my $row = $sth->fetchrow_hashref() )
	{
	    push @data, $row;
	}

	return @data;
    }
}

1;
